package com.example.shiro.demo.service;

import com.example.shiro.demo.dao.PermissionDao;
import com.example.shiro.demo.dao.RoleRepository;
import com.example.shiro.demo.dao.UserRepository;
import com.example.shiro.demo.entity.Permission;
import com.example.shiro.demo.entity.Role;
import com.example.shiro.demo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class AuthorityService {

    @Autowired
    private UserRepository userDao;

    public List<Object> findByUserId(Long id) {
        Optional<User>  user = userDao.findById(id);
        List<Object> permissionsList = new ArrayList<>();
        if (user.isPresent()){
            User userPo = user.get();
            List<Role> roles = userPo.getRoles();
            if (roles!=null && !roles.isEmpty() ){
                roles.stream().forEach( e->{
                    List<Permission> objList =  e.getPermissions();
                    if (objList!=null && !objList.isEmpty()){
                        objList.stream().forEach(p->{
                            permissionsList.add((Object)p.getPermission());
                        });

                    }
                } );
            }
        }
        return permissionsList;
    }
}
